import { message } from "antd";
import axios from "axios"; //封装axios，让axios具有其他的功能

const newAxios = axios.create({
  baseURL: "/api", //请求网址开头标识，配合代理服务器
  timeout: 5000, //请求反应时间
});

newAxios.interceptors.request.use(
  //请求处理
  (res) => {
    if (localStorage.token) {
      res.headers.Authorization = localStorage.token;
    }
    return res;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

newAxios.interceptors.response.use(
  //响应处理
  (res) => {
    return res; //统一处理响应数据
  },
  (error) => {
    //处理不同情况下的异常
    switch (error.response.status) {
      case 401:
        message.error({
          content: "身份信息过期，请重新登陆",
          duration: 2,
          onClose: () => {
            //跳转至登录界面
            location.href = "/";
          },
        });
        break;
      case 400:
        message.error({
          content: "服务器无法理解，请求错误",
          duration: 2,
        });
        break;
      case 500:
        message.error({
          content: "请求失败，服务器错误",
          duration: 2,
        });
        break;
      default:
        message.error({
          content: "其他错误",
          duration: 2,
        });
        break;
    }
    return Promise.reject(error);
  }
);

export default newAxios;